/*
 * Buffer.cpp
 *
 *  Created on: 22.03.2010
 *      Author: pascalmuller
 */

#include "Buffer.h"
#include <iostream>

Buffer::Buffer(char* filename) {
	buffer_size = 5;
	this->buffer1 = new char[this->buffer_size];
	this->buffer2 = new char[this->buffer_size];
	this->currentIndex	= -1;
	this->isUngetChar   = false;
	// Open file.
	this->sourcecode = fopen(filename,"r");

	if (this->sourcecode == NULL) {
		//TODO: Exception!!!!!
		std::cout << "FEHLER: datei fehlt" << std::endl;
	} else {
		this->currentBuffer = this->buffer1;
		fread (this->currentBuffer,1,this->buffer_size,this->sourcecode);
	}
}
Buffer::~Buffer() {
	delete[] buffer1;
	delete[] buffer2;
}

void Buffer::switchBuffer(){
	if (this->currentBuffer == this->buffer1){
		this->currentBuffer = this->buffer2;
	} else {
		this->currentBuffer = this->buffer1;
	}
}

void Buffer::reloadBuffer(){
	switchBuffer();
	//lese Daten
	fread (this->currentBuffer,1,this->buffer_size,this->sourcecode);
}


// currentIndex = 0
//
char Buffer::getChar(){

	this->currentIndex++;
	//wenn am Ende des Buffers => reload
	if(this->currentIndex >= this->buffer_size){
		this->currentIndex = 0;
		if (this->isUngetChar){
			switchBuffer();
			this->isUngetChar = false;
		} else {
			printf("<Lade>");
			reloadBuffer();
		}
	}

	return currentBuffer[this->currentIndex];
}

/**
** wird am anfang bestimmt nicht aufgerufen...
*/
char Buffer::ungetChar(){
	// wenn am anfang eines Buffers
	// und der Scanner will ungetChar()...
	--this->currentIndex;

	if(this->currentIndex < 0){
		switchBuffer();
		this->currentIndex = this->buffer_size-1;
		this->isUngetChar = true;
	}

	return currentBuffer[this->currentIndex];
}


int main()
{
	Buffer v1("test.txt");

	for(int i = 0; i < 6; i++)
	{
		std::cout << v1.getChar();
	}
	std::cout << std::endl;
	std::cout << v1.ungetChar() << std::endl;
	std::cout << v1.getChar() << std::endl;


	return 1;
}
